#!/usr/bin/env python
# -*- coding:utf-8 -*-

from bottle import Bottle
from bottle import request, response

from conn.MyPagerFactory import MyPager

memberAdm = Bottle()


@memberAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@memberAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class MemebersRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "991": "处理参数错误, 请填写 %s",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
        "110": "关键数据重复，数据处理失败",
    }

    MEMBER_REG_PARAM = [
        {"key": "register_type", "val": "注册来源"}, {"key": "name", "val": "姓名"},
        {"key": "uname", "val": "手机号"}, {"key": "sex", "val": "性别"}, {"key": "age", "val": "年龄"},
        {"key": "height", "val": "身高"}, {"key": "weight", "val": "体重"}
    ]

    impl = None
    times_array = []

    def __init__(self, service):
        MemebersRoute.impl = service
        return

    @staticmethod
    @memberAdm.get('/fetch')
    def fetch():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        res = MemebersRoute.impl.fetch(param=params)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["99"]}
        view_list = res['data']
        _pages = MyPager.make_pager(id="table_members", res=view_list, page_size=int(params['pageSize']),
                                    data_total=res['total'], single_pager=False)
        return {'code': 200, 'data': _pages, 'message': ""}

    @staticmethod
    @memberAdm.get('/fetchOne')
    def fetch_one():
        memberId = request.params.memberId
        res = MemebersRoute.impl.fetch_one(member_id=memberId)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["99"]}
        view = res['data'][0]
        return {'code': 200, 'data': view, 'message': ""}

    @staticmethod
    @memberAdm.post('/add')
    def add():
        if request.json is not None:
            data = request.json['data']
            res = MemebersRoute.impl.add_member(member=data)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["100"]}

    @staticmethod
    @memberAdm.post('/update')
    def update():
        if request.json is not None:
            data = request.json['data']
            memberId = data['member_id']
            res = MemebersRoute.impl.update_member(member=data, member_id=memberId)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            elif res['code'] == 404:
                return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
            else:
                return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["102"]}

    @staticmethod
    @memberAdm.get('/drop')
    def drop():
        memberId = request.params.memberId
        res = MemebersRoute.impl.drop_member(member_id=memberId)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["103"]}
        elif res['code'] == 404:
            return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
        return {'code': 200, 'data': None, 'message': ""}

    @staticmethod
    @memberAdm.get('/res')
    def res():
        memberId = request.params.memberId
        res = MemebersRoute.impl.res_member(member_id=memberId)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["105"]}
        elif res['code'] == 404:
            return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
        return {'code': 200, 'data': None, 'message': ""}

    @staticmethod
    @memberAdm.get('/act')
    def act():
        memberId = request.params.memberId
        res = MemebersRoute.impl.act_member(member_id=memberId)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["106"]}
        elif res['code'] == 404:
            return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
        return {'code': 200, 'data': None, 'message': ""}

    @staticmethod
    @memberAdm.get('/stop')
    def stop():
        memberId = request.params.memberId
        res = MemebersRoute.impl.stop_member(member_id=memberId)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["104"]}
        elif res['code'] == 404:
            return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
        return {'code': 200, 'data': None, 'message': ""}

    @staticmethod
    @memberAdm.post('/reg')
    def reg():
        import json
        import urllib.parse
        if request.json is not None:
            str_json_data = request.json['data']
            decoded_string = urllib.parse.unquote(string=str_json_data,encoding='utf-8')
            str_times = request.json['times']
            if str_times in MemebersRoute.times_array:
                return
            else:
                MemebersRoute.times_array.append(str_times)
            data = json.loads(decoded_string)
            err = MemebersRoute.check_param_none(data)
            if err is None:
                # 优先执行 MEM的注册流程，然后调用计算的会员信息绑定流程
                res = MemebersRoute.impl.reg_member(member=data)
                if res["code"] != 200:
                    if res["code"] == 501:
                        return {'code': 110, 'data': None, 'message': MemebersRoute.ERROR_CODE["110"]}
                    else:
                        return {'code': 99, 'data': None, 'message': MemebersRoute.ERROR_CODE["100"]}
                elif res['code'] == 404:
                    return {'code': res['code'], 'data': res, 'message': MemebersRoute.ERROR_CODE["109"]}
                return {'code': 200, 'data': None, 'message': ""}
            else:
                return err

    @staticmethod
    def check_param_none(val) -> {}:
        for item_index in range(len(MemebersRoute.MEMBER_REG_PARAM)):
            try:
                _check_item = MemebersRoute.MEMBER_REG_PARAM[item_index]
                _check_key = val[_check_item['key']]
                if isinstance(_check_key, str):
                    if _check_key is None or len(_check_key) == 0:
                        _str_error_message = MemebersRoute.ERROR_CODE["991"] % _check_item['val']
                        return {'code': 99, 'data': None, 'message': _str_error_message}
            except KeyError as e:
                continue
        return None
